//go:generate go run gen_graphql.go

// Package graphql contains the root GraphQL http handler
package graphql

import (
	"net/http"
	"time"

	"github.com/99designs/gqlgen/handler"
	"github.com/gorilla/websocket"

	"happy-sudoku/graphql/graph"
	"happy-sudoku/graphql/resolvers"
	"happy-sudoku/internal/middleware"
)

// Handler is the root GraphQL http handler
type Handler struct {
	http.HandlerFunc
	*resolvers.RootResolver
}

// NewHandler new graphql handler
func NewHandler(cfg resolvers.ResolverConfig, directive graph.DirectiveRoot) (Handler, error) {
	h := Handler{
		RootResolver: resolvers.NewRootResolver(cfg),
	}

	config := graph.Config{
		Resolvers:  h.RootResolver,
		Directives: directive,
	}
	websocketUpgrader := handler.WebsocketUpgrader(websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		}},
	)

	websocketKeepalive := handler.WebsocketKeepAliveDuration(time.Second * 5)

	h.HandlerFunc = handler.GraphQL(
		graph.NewExecutableSchema(config),
		websocketUpgrader,
		websocketKeepalive,
		handler.WebsocketInitFunc(
			middleware.AuthWsMiddleware(cfg.AuthSrv),
		),
		handler.ErrorPresenter(middleware.GQLErrorPresenter),
	)

	return h, nil
}
